const path = require('path')
const { base64ToImg } = require('../utils/imgUtil')
const fs = require('fs')


class UploadController {
	async uploadAvatar(req, res, next) {
		const { userId, content } = req.body
		console.log(userId, content);
		const dir = path.join(__dirname, '../public/img/avatar')
		const filename = await base64ToImg(content, dir)
		console.log(filename);

		try {
			let userPath = path.join(__dirname, '../data/users.json');
			const users = JSON.parse(fs.readFileSync(userPath, 'utf8')).users;
			const index = users.findIndex(user=>user.id == userId)
			users[index].avatar = `http://10.41.154.18:3000/img/avatar/${filename}`;
			fs.writeFileSync(userPath, JSON.stringify({ users: users }))
			res.json({
				code: 200,
				msg: "设置成功",
				data:{
					url: `http://10.41.154.18:3000/img/avatar/${filename}`
				}
			})
		} catch(error) {
			console.log(error);
			res.json({
				code: 200,
				msg: "设置成功",
				error
			})
		}
	}

	async uploadGender(req, res, next) {
		const { userId, gender } = req.body
		console.log(userId, gender);
		try {
			let userPath = path.join(__dirname, '../data/users.json');
			const users = JSON.parse(fs.readFileSync(userPath, 'utf8')).users;
			const index = users.findIndex(user=>user.id == userId)
			users[index].gender = gender;
			fs.writeFileSync(userPath, JSON.stringify({ users: users }))
		} catch(e) {
			console.log(e);
		}
	}

	async uploadName(req, res, next) {
		const { userId, name } = req.body
		console.log(userId, name);
		try {
			let userPath = path.join(__dirname, '../data/users.json');
			const users = JSON.parse(fs.readFileSync(userPath, 'utf8')).users;
			const index = users.findIndex(user=>user.id == userId)
			users[index].name = name;
			fs.writeFileSync(userPath, JSON.stringify({ users: users }))
		} catch(e) {
			console.log(e);
		}
	}

	async uploadBirth(req, res, next) {
		const { userId, birth } = req.body
		console.log(userId, birth);
		try {
			let userPath = path.join(__dirname, '../data/users.json');
			const users = JSON.parse(fs.readFileSync(userPath, 'utf8')).users;
			const index = users.findIndex(user=>user.id == userId)
			users[index].birth = birth;
			fs.writeFileSync(userPath, JSON.stringify({ users: users }))
		} catch(e) {
			console.log(e);
		}
	}
}

module.exports = new UploadController();